<template>
  <div>
    <!-- 此文件为详情轮播图 -->
    <!-- 头部 -->
    <van-sticky>
      <deback-index>
        <van-icon
          name="arrow-left"
          class="icon-one"
          @click="$router.push('/index')"
        />
        <h5>{{ conn.title }}</h5>
      </deback-index>
    </van-sticky>
    <!-- 轮播图部分 -->
    <div v-if="!load && !loadfalse" style="text-align: center; font-size: 16px">
      <van-loading size="30px" text-size="14px" color="#000"
        >加载中, 请稍后</van-loading
      >
    </div>
    <p
      style="
        text-align: center;
        font-size: 16px;
        color: #d2d2d2;
        margin-top: 100px;
      "
      v-if="loadfalse"
    >
      <span
        ><van-image
          :src="require('../images/失败.svg')"
          width="12"
          height="12"
        />
        加载失败！！请检查你的网络或联系工作人员</span
      >
    </p>
    <div v-if="load">
      <detail-swipe :banner="banner"></detail-swipe>
      <!-- 文字加横向滚动 -->
      <line-list
        :arr="arr"
        :showPrice="showPrice"
        :desc="desc"
        :title="title"
      ></line-list>
      <div class="popup">
        <ul class="ulfirst">
          <li class="lione">
            <van-cell @click="showPopup('btn1')">
              <span>已选:</span>
              <span>{{ checkgoodsSkus }}</span>
            </van-cell>
            <van-popup
              v-model="show"
              round
              position="bottom"
              :style="{ height: '70%' }"
            >
              <div class="tanchuang">
                <div class="left">
                  <van-image
                    width="100"
                    height="100"
                    :src="require('../images/demo/cate_02.png')"
                  />
                </div>
                <div class="right">
                  <p><span>￥</span>{{ showPrice }}</p>
                  <p>{{ checkgoodsSkus }}</p>
                </div>
                <div style="clear: both"></div>

                <div v-for="(item, index) in selects" :key="index">
                  <p>{{ item.title }}</p>
                  <!-- 12/27 -->
                  <debtns
                    :label="item"
                    :num="index"
                    @btnClick="itemClick(arguments)"
                  ></debtns>
                  <!-- <debtns></debtns> -->
                </div>
                <div>
                  <span>
                    购买数量
                    <van-stepper
                      style="float: right; display: inline-block; width: 100px"
                      v-model="value"
                      :max="stock"
                    />
                  </span>
                </div>
                <!-- <div class="btnp" @>
                <p>加入购物车</p>
              </div> -->
                <van-button class="btnp" type="default" block @click="toCart"
                  >加入购物车</van-button
                >
              </div>
            </van-popup>
            <!-- <span>已选</span> -->
          </li>
        </ul>
        <ul class="ulfirst">
          <li>
            <van-cell @click="showPopup('btn2')">
              <span> 配送： </span>
              <span v-if="pathList.length > 0"
                ><span style="color: red; font-weight: 900"
                  >{{ pathList[0].value.slice(0, 7) }}
                </span>
                现配</span
              >
              <span v-else>点击添加新地址</span>
            </van-cell>
            <van-popup
              v-model="showtwo"
              round
              position="bottom"
              :style="{ height: '70%' }"
            >
              <div>
                <h5 class="h5">收货地址</h5>
                <van-divider
                  :style="{ padding: 0, height: '20px', margin: 0 }"
                />
                <ul class="popuptwoul">
                  <li
                    v-if="pathList.length == 0"
                    style="text-align: center; color: orange"
                  >
                    <p>地址为空，快去点击下方按钮添加新地址吧！</p>
                      <van-button class="btnp" type="default" block to="address"
                      >选择新的地址</van-button
                    >
                  </li>
                  <li
                    v-for="(item, index) in pathList"
                    :key="index"
                    class="popuptwo"
                  >
                    <van-swipe-cell stop-propagation>
                      <p><van-icon name="location" />{{ item.text }}</p>
                      <p>
                        <span>
                          {{ item.path }}
                        </span>
                        <span>
                          {{ item.address }}
                        </span>
                      </p>
                      <template #right>
                        <van-button
                          square
                          type="info"
                          text="编辑"
                          @click="edit(item, index)"
                        />
                        <van-button
                          square
                          type="danger"
                          text="删除"
                          @click="deleteSwipe(index)"
                        />
                      </template>
                    </van-swipe-cell>

                    <van-button class="btnp" type="default" block to="address"
                      >选择新的地址</van-button
                    >
                  </li>
                </ul>
              </div>
            </van-popup>
          </li>
        </ul>
        <ul class="uls">
          <van-cell @click="showPopup('btn3')">
            <li>
              <span><van-icon name="passed" color="red" /></span>
              <span class="lispan">小米自营</span>
            </li>
            <li>
              <span><van-icon name="passed" color="red" /></span>
              <span class="lispan">小米发货</span>
            </li>
            <li>
              <span><van-icon name="passed" color="red" /></span>
              <span class="lispan">七天无理由发货</span>
            </li>
          </van-cell>
          <van-popup
            v-model="showthree"
            round
            position="bottom"
            :style="{ height: '70%' }"
          >
            <div>
              <h5 class="h5">服务说明</h5>
              <van-divider :style="{ padding: 0, height: '20px', margin: 0 }" />
              <div>
                <span style="margin: 0 5px; font-size: 16px"
                  ><van-icon name="passed" color="red" />&nbsp;小米自营</span
                >
                <p style="margin: 0 25px; font-size: 10px; color: #bbb">
                  不管满多少，就是不包邮
                </p>
              </div>
            </div>
          </van-popup>
        </ul>
        <div v-html="img" @click="imageChgange($event)"></div>
      </div>
    </div>
  </div>
</template>

<script>
var htmlString = `
	<p class="p1">
		<img src="https://i8.mifile.cn/v1/a1/9c3e29dc-151f-75cb-b0a5-c423a5d13926.webp">
		<img src="https://i8.mifile.cn/v1/a1/f442b971-379f-5030-68aa-3b0accb8c2b9.webp">
		<img src="https://i8.mifile.cn/v1/a1/63b700b6-643e-ec18-fdf3-da66b4b4173f.webp">
		<img src="https://i8.mifile.cn/v1/a1/e9dbf276-193e-11c4-99a6-3097fde82350.webp">
		<img src="https://i8.mifile.cn/v1/a1/1249d3ee-2990-a2b4-28d9-f719c2417b1f.webp">
		<img src="https://i8.mifile.cn/v1/a1/97c79915-64b2-808c-53b4-4345652a179f.webp">
		<img src="https://i8.mifile.cn/v1/a1/cd0fbe1e-a1b3-a87a-f4a6-6fb08ec54931.webp">
	</p>`;
import DebackIndex from "../components/debackIndex.vue";
import detailSwipe from "../components/detail-swipe.vue";
import LineList from "../components/lineList.vue";
import debtns from "../components/debtns.vue";
import { mapMutations, mapState } from "vuex";
import { Toast } from "vant";
import { Dialog } from "vant";
import { ImagePreview } from "vant";
export default {
  components: { detailSwipe, DebackIndex, LineList, debtns },
  name: "Detail",

  data() {
    return {
      img: "",
      active: true,
      conn: {},
      title: "",
      banner: [],
      desc: "",
      detail: "",
      goodsAttrs: [],
      arr: [],
      // 弹出层样式
      show: false,
      showtwo: false,
      showthree: false,
      // 步进器
      value: 1,
      user: "",
      selects: [
        /*  {
          title: "颜色",
          selected: 0,
          list: [
            {
              name: "黄色",
            },
            {
              name: "黑色",
            },
          ],
        },
        {
          title: "套餐",
          selected: 0,
          list: [
            {
              name: "标配",
            },
            {
              name: "套餐1",
            },
          ],
        }, */
      ],

      load: false,
      loadfalse: false,
    };
  },

  mounted() {
    this.load = false;
    var user = window.sessionStorage.getItem("token");
    console.log(user);
    if (user) {
      user = JSON.parse(user);
      this.user = user;
    }

    // console.log(user);
    this.file();
    this.ddetail();
    this.img = htmlString;
    // console.log(this.img);
  },
  methods: {
    //ImagePreview  Vant组件库图片预览组件
    imageChgange(e) {
      console.log(e);
      console.log(e.target.currentSrc);
      if (e.target.nodeName == "IMG") { //判断他的类型是不是img
        ImagePreview({
          images: [e.target.currentSrc], //e.target.currentSrc  当前图片src
          showIndex: false,
          loop: false,
        });
      } else {
        return;
      }
    },
    ...mapMutations(["deladdress", "updatePath"]),
    // 左滑编辑效果实现
    edit(item, index) {
      console.log(item);
      let obj = {
        index: index,
        item: item,
      };
      console.log("编辑" + index);
      this.$router.push({
        path: "/address",
        query: {
          edit: JSON.stringify(obj),
        },
      });
    },
    // 左滑删除效果实现
    deleteSwipe(index) {
      Dialog.confirm({
        title: "是否确认删除？",
        message: "删除后将无法找回",
      })
        .then(() => {
          Toast("删除成功！");
          this.deladdress(index);
        })
        .catch(() => {
          // on cancel
        });

      console.log("删除" + index);
    },
    //
    // 弹出层方法
    showPopup(a) {
      if (a === "btn1") {
        this.show = true;
      } else if (a === "btn2") {
        this.showtwo = true;
      } else if (a === "btn3") {
        this.showthree = true;
      }
    },
    //
    itemClick(e) {
      console.log(e);
      var ind = e[0];
      console.log(ind);
      var num = e[1];
      this.selects[num].selected = ind;
    },
    file() {
      //   return this.$route.query.detail;
      var con = JSON.parse(this.$route.query.detail);
      return (this.conn = con);
    },
    ddetail() {
      this.$axios
        .get(`/goods/${this.conn.id}`)
        .then((v) => {
          this.load = true;
          console.log(v);
          this.banner = v.data.data.goodsBanner;
          this.detail = v.data.data;
          this.detail.num = 1;
          console.log(v.data.data.content);
          this.title = v.data.data.title;
          this.desc = v.data.data.desc;
          this.goodsAttrs = v.data.data.goodsAttrs;
          this.goodsAttrs.forEach((v) => {
            this.arr.push(v);
          });

          this.selects = v.data.data.goodsSkusCard.map((res) => {
            var list = res.goodsSkusCardValue.map((item) => {
              return {
                id: item.id,
                name: item.value,
              };
            });
            // console.log(list);
            return {
              id: res.id,
              selected: 0,
              title: res.name,
              list: list,
            };
          });
          v.data.data.goodsSkus.map((res) => {
            // console.log(res.stock);
            let arr = [];
            // 对象用for in遍历
            for (let key in res.skus) {
              // key值为每个按钮的索引值
              // console.log(res.skus[key]);
              arr.push(res.skus[key].value);
            }
            // console.log(arr);
            // 新建一个skusText放在数据中
            res.skusText = arr.join(",");
            // console.log(res.skusText);
            // 0:54:53
          });
        })
        .catch((error) => {
          setTimeout(() => {
            this.loadfalse = true;
            Toast("加载失败，请检查您的网络");
          }, 5000);
        });
    },
    // 加入购物车
    toCart() {
      var shop_id =
        this.detail.sku_type === 0
          ? this.detail.id
          : this.detail.goodsSkus[this.checkgoodsSkusIndex].id;
      console.log(shop_id);
      // 这个skus_type就是请求数据中的单规格与多规格
      var skus_type = this.detail.sku_type;
      console.log(skus_type);

      // num商品数量
      var num = this.value;
      console.log(num);
      // console.log(require);
      // console.log(this.status);
      if (this.status == 1) {
        this.$axios({
          url: `/cart`,
          method: "POST",
          data: {
            shop_id: shop_id,
            skus_type: skus_type,
            num: num,
          },
          headers: {
            token: true,
          },
        })
          .then((v) => {
            console.log(v);
            console.log(v.config);
            Toast("添加成功，正在前往购物车页面......");
            this.$bus.$emit("updateCartList");
            return setTimeout(() => {
              this.$router.push("/cart");
            }, 1000);
          })
          .catch(function (error) {
            if (error.response) {
              // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
              console.log(error.response.data);
              console.log(error.response.status);
              console.log(error.response.headers);
            } else if (error.request) {
              // 请求已经成功发起，但没有收到响应
              // `error.request` 在浏览器中是 XMLHttpRequest 的实例，
              // 而在node.js中是 http.ClientRequest 的实例
              console.log(error.request);
            } else {
              // 发送请求时出了点问题
              console.log("Error", error.message);
            }
          });
      } else {
        Toast({
          message: "请登录",
          duration: 3000,
          forbidClick: true,
        });
        this.$router.push("/login");
      }
    },
  },
  computed: {
    ...mapState({
      status: (state) => state.user.status,
      pathList: (state) => state.page.pathList,
    }),
    // 请求头数据
    /*     ...mapState({
      token: (state) => state.user.token,
    }), */
    // 获取对应的按钮值用join拼接起来
    checkgoodsSkus() {
      var checkgoodsSkus2 = this.selects.map((v) => {
        console.log(v);
        return v.list[v.selected].name;
        // console.log(v.list[v.selected].name);
      });
      return checkgoodsSkus2.join(",");
    },
    // 查找到的索引值
    checkgoodsSkusIndex() {
      if (this.detail.goodsSkus) {
        var index = this.detail.goodsSkus.findIndex((v) => {
          return this.checkgoodsSkus === v.skusText;
        });
        return index;
      } else {
        return -1;
      }
    },
    showPrice() {
      var index = this.checkgoodsSkusIndex;
      if (this.detail.goodsSkus) {
        // console.log(this.detail.goodsSkus[index].pprice);
        return this.detail.goodsSkus[index].pprice;
      } else {
        return this.detail.min_price;
      }
    },
    // 获取最大值
    stock() {
      var index = this.checkgoodsSkusIndex;
      // console.log(index);
      if (this.detail.goodsSkus) {
        return this.detail.goodsSkus[index].stock;
      } else {
        return;
      }
    },
  },
};
</script>

<style scoped>
.popup {
  background-color: rgb(238, 238, 238);
  width: 95%;
  margin: 0 auto;
  /* margin: 0 20px; */
  /* box-sizing: border-box; */
  /* height: 100px; */
}
.lispan {
  color: rgb(111, 120, 128);
}
.ulfirst li {
  padding: 0 10px;
  box-sizing: border-box;
  /* height: 30px; */
}
.uls {
  height: 40px;
}
.uls li {
  float: left;
  margin: 0 5px;
  height: 30px;
}
.van-cell {
  background-color: rgba(0, 0, 0, 0);
  padding: 10px 0 0 0;
  color: black;
}
.tanchuang {
  margin: 20px;
}
.tanchuang img {
  width: 100px;
  height: 100px;
}
/* 图片以及文字部分 */

.left {
  float: left;
}
.right {
  float: left;
  width: 50%;
  padding-top: 25px;
  height: 50px;
  color: orange;
  font-weight: bold;
}
.btnp {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 1.066667rem;
  background: rgb(255, 102, 0);
  color: #fff;
  text-align: center;
}

.popuptwo p:nth-child(1) {
  font-size: 16px;
  margin-bottom: 5px;
  font-weight: bold;
}
.popuptwo p:nth-child(2) {
  margin-bottom: 10px;
  color: #b2b2b2;
}
.h5 {
  font-weight: 600;
  font-size: 18px;
  text-align: center;
  padding: 10px 0;
  box-sizing: border-box;
}
.popuptwoul {
  height: 9.333333rem;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}
.icon-one {
  margin-left: 0.133333rem;
  font-size: 0.533333rem;
  width: 10%;
}
::v-deep .p1 img {
  width: 100% !important;
}
::v-deep .p1 {
  line-height: 0 !important;
}
</style>
